package utils.http
{
	import application.Application;
	import application.ApplicationConstants;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	
	import mx.controls.Alert;
	
	public class HttpConnector
	{
		private var request:URLRequest;
		
		public var url:String;
		public var method:String;
		public var headers:Array;
		public var contentType:String = "application/x-www-form-urlencoded";
		public var content:String;
		
		public var sendToken:Boolean = true;
		public var verifyToken:Boolean = true;
		
		public var successFunction:Function;
		public var failureFunction:Function;
		
		private var httpStatusEvent:HTTPStatusEvent;
		
		public var responseData:String;
		
		public function HttpConnector()
		{
		}
		
		public function connect():void {
			request = new URLRequest(url);
			request.method = method;
			request.data = content;
			request.contentType = contentType;
			
			if (sendToken) {
				var token:String = Application.get().getAttribute(ApplicationConstants.TOKEN_ATTR) as String;
				
				var tokenHeader:URLRequestHeader = new URLRequestHeader(ApplicationConstants.TOKEN_HEADER, token);
				request.requestHeaders.push(tokenHeader);
			}
			
			var loader:URLLoader = new URLLoader();
			
			loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, responseStatus);
			loader.addEventListener(Event.COMPLETE, complete);
			
			loader.load(request);
		}
		
		public function complete(event:Event):void {
			var loader:URLLoader = event.target as URLLoader;
			
			var responseData:String = loader.data;
			
			if (httpStatusEvent != null) {
					switch (httpStatusEvent.status) {
						case 200:
							var tokenReceived = verifyToken ? verifyTokenFromResponse(httpStatusEvent) : true;
							
							if (tokenReceived) {
								var success:SuccessResponse = new SuccessResponse(responseData, httpStatusEvent.responseHeaders);
								successFunction.apply(this, [success]);
							} else {
								var failure:FailureResponse = new FailureResponse(httpStatusEvent.status, "Token não recebido!");
								failureFunction.apply(this, [failure]);
							}
						break;
						
						default:
							var failure:FailureResponse = new FailureResponse(httpStatusEvent.status, responseData);
							failureFunction.apply(this, [failure]);
						break;
					}
			} else {
				var failure:FailureResponse = new FailureResponse(-1, "Erro no sistema cliente.");
				failureFunction.apply(this, [failure]);
			}
		}
		
		private function verifyTokenFromResponse(event:HTTPStatusEvent):Boolean {
			var headers:Array = event.responseHeaders;
			for (var i:int = 0; i < headers.length; i++) {
				var header:URLRequestHeader = headers[i];
				if (header.name == ApplicationConstants.TOKEN_HEADER) {
					//Alert.show("Headers: " + header.name + " - " + header.value);
					Application.get().addAttribute(ApplicationConstants.TOKEN_ATTR, header.value);
							
					return true;
				}
			}
			
			return false;
		}
		
		public function responseStatus(event:HTTPStatusEvent):void {
			httpStatusEvent = event;
		}

		public function onSuccess(success:Function):void {
			this.successFunction = success;
		}

		public function onFailure(failure:Function):void {
			this.failureFunction = failure;
		}

	}
}